package br.jus.tjpe.dao;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import br.jus.tjpe.dominio.Parte;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ParteDaoImpl extends DaoGenericoBase<Parte> implements ParteDao {

	@SuppressWarnings("unchecked")
	public List<Parte> consultarPartes(String nome) {
		List<Parte> partes = new ArrayList<Parte>();
		EntityManager em = getEntityManager();
		StringBuffer queryString = new StringBuffer();
		queryString.append(" select pf from ParteFisica pf where pf.nome like :nome");
		queryString.append("  union");
		queryString.append(" select pj from ParteJuridica pj where pj.razaoSocial like :nome");
		
		Query query = em.createQuery(queryString.toString());
		query.setParameter("nome", "%" + nome + "%");
		partes = query.getResultList();

		return partes;
	}
	
	@Resource
	private SessionContext context;

	@Override
	public <E> E inserir(E entidade) throws PersistenceException {
		E entity = null;
		UserTransaction ut = context.getUserTransaction();
		try {
			ut.begin();
			entity = super.inserir(entidade);
			ut.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	@Override
	public <E> E editar(E entidade) throws PersistenceException {
		E entity = null;
		UserTransaction ut = context.getUserTransaction();
		try {
			ut.begin();
			entity = super.editar(entidade);
			ut.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}
	
	@Override
	public <E> E remover(E entidade) throws PersistenceException {
		E entity = null;
		UserTransaction ut = context.getUserTransaction();
		try {
			ut.begin();
			entity = super.remover(entidade);
			ut.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}
}
